package com.example.flashsales.interceptor;


import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.flashsales.Tools.BeanUtils;
import com.example.flashsales.Tools.TokenTool;
import com.example.flashsales.entity.Result;
import com.example.flashsales.entity.vo.AdminVo;
import com.example.flashsales.service.impl.AdminServiceImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class RoleInterceptor  extends HandlerInterceptorAdapter {


    AdminServiceImpl adminService = BeanUtils.getBean(AdminServiceImpl.class);

    /**
     * 进入Controller之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @SneakyThrows
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Content-Type");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
        response.setHeader("Access-Control-Allow-Methods", "POST,GET");
        response.addHeader("Access-Control-Expose-Headers","Token");
        String token = request.getHeader("Token");
        if (token == null || token.equals("")){
            request.setAttribute("str","身份错误");
            log.error("Token为空");
            final String s = JSON.toJSONString(Result.error("身份异常").setCode("404"));
            response.getWriter().append(s);
            return false;
        }

        int userId = 0;
        try{
            //验证Token
            TokenTool.verify(token);
            //拿到Token里面用户的数据
            DecodedJWT token1 = TokenTool.getToken(token);
            String id = token1.getClaim("id").asString();
            userId = Integer.parseInt(id);
            final AdminVo adminVo = adminService.viewAdminMessage(userId);
            if (adminVo.getState() != 4){
                //token过期
                final String s = JSON.toJSONString(Result.error("抱歉你没有权限").setCode("404"));
                response.getWriter().append(s);
                return false;
            }
            String phone = token1.getClaim("phone").asString();
            request.setAttribute("id",id);
            Map<String,String> map = new HashMap<>();
            map.put("id",id);
            map.put("phone", phone);
            response.setHeader("Token",TokenTool.createToken(map));
            log.info("请求成功");
        }catch (JWTDecodeException e){
            //token格式错误
            final String s = JSON.toJSONString(Result.error("身份异常").setCode("404"));
            response.getWriter().append(s);
            log.error("Token格式错误");
            return false;
        }catch (TokenExpiredException e){
            //token过期
            final String s = JSON.toJSONString(Result.error("登录过期").setCode("404"));
            response.getWriter().append(s);
            log.error("Token过期");
            return false;
        }catch (AlgorithmMismatchException e){
            //token算法不一致
            final String s = JSON.toJSONString(Result.error("身份异常").setCode("404"));
            response.getWriter().append(s);
            log.error("Token算法不一致");
            return false;
        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }

    /**
     * preHandle之后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
